<?php
namespace app\admin\controller;

use app\admin\model\Agent as AgentModel;
use app\admin\model\AgentGroup as AgentGroupModel;
use app\admin\model\AdminGroup as AdminGroupModel;
use app\admin\model\AgentLevel as AgentLevelModel;
use app\admin\model\Region as RegionModel;
use think\Db;
use think\Request;

class Agent extends Base
{
    public function index()
    {
        $model = new AgentModel;
        $agModel = new AgentGroupModel;
        $alModel = new AgentLevelModel;
        $reModel = new RegionModel;

        //渲染页面模板
        // $m = $model->field('a.id,a.code,a.name,a.linkman,a.mobile,a.device,a.registered_at,g.name as groupname, l.name as levelname,r.name as regname ')
        $model->field('a.id,a.code,a.name,a.linkman,a.mobile,a.device,a.registered_at,g.name as groupname, l.name as levelname,r.name as regname ,d.countid')
            ->alias('a')
            ->join('franchiser_group g','a.franchiser_group_id = g.id','left')
            ->join('franchiser_level l','a.franchiser_level_id = l.id','left')
            ->join('region r','a.region_id = r.id','left')
            ->join('(SELECT franchiser_id, COUNT(id) as countid from '. $this->dbTablePrefix .'device GROUP BY franchiser_id HAVING franchiser_id>0) d','a.id = d.franchiser_id ','left')
            ->order('a.id','desc');
        //->select();
        // ->paginate(5);

        //搜索名称
        $phname = $this->request->param("phname");

        if(!empty($phname)){
            // $m =  $m->where('a.name | a.mobile','like', '%'.$phname.'%');
            $model->where('a.name','like', '%'.$phname.'%');
        }
        // $result = $m->paginate(5,false,[
        $result = $model->paginate(10,false,[
            'query'=>['phname'=>$phname]
        ]);

        //渲染用户组
        $aGroup = $agModel->field('id,name')->select();
        //渲染代理商
        $alevel = $alModel->field('id,name')->select();

        //计算总共记录条数
        $count = $result->total();
        //分页
        $page = $result->render();

        //接收ajax传递的值
        $request = request();
        $ispost = $request->isPost();
        if($ispost){
            $id = $_POST["viewId"];
            $region = \think\Db::query('SELECT r.id ,r.p_id ,r.name FROM '. $this->dbTablePrefix .'franchiser as f left join '. $this->dbTablePrefix .'region as r on r.id=f.region_id where f.id='.$id );
            $city = \think\Db::query('SELECT id,p_id,name FROM '. $this->dbTablePrefix .'region where id='.$region[0]["p_id"] );
            $pro = \think\Db::query('SELECT id,p_id,name FROM '. $this->dbTablePrefix .'region where id='.$city[0]["p_id"] );
            $arrcity = \think\Db::query('SELECT id,p_id,name FROM '. $this->dbTablePrefix .'region where p_id='.$city[0]["id"] );
            $arrpro = \think\Db::query('SELECT id,p_id,name FROM '. $this->dbTablePrefix .'region where p_id='.$pro[0]["id"] );
            $view = $model->getAll()->where("id",$id)->find();
            $view["area"] = $region[0]["id"];
            $view["city"] = $city[0]["id"];
            $view["province"] = $pro[0]["id"];

            return json([
                'code' => 200,
                'view'=>$view,
                'arrpro'=>$arrpro,
                'arrcity'=>$arrcity,
            ]);
        }


        $this->assign('currentPage',$result->currentPage());
        $this->assign('lastPage',$result->lastPage());
        $this->assign('page',$page);
        $this->assign('aGroup',$aGroup);
        $this->assign('alevel',$alevel);
        //$this->assign('region',$region);
        $this->assign('agent',$result);
        $this->assign('count',$count);
        $this->assign('empty',"暂无数据");
        return $this->fetch();
    }

    //新增数据
    public function create()
    {
        $model = new AgentModel;
        //接收ajax传递的值
        $ispost = $this->request->isPost();
        if($ispost){
            $formdata = $this->request->post();
            unset($formdata["province"]);
            unset($formdata["city"]);
            $formdata["region_id"] = $formdata["area"];
            $username = Db::query("select id,name from ". $this->dbTablePrefix ."franchiser where `name`='".$formdata['name']."' and deleted_at is NULL ");

            if(!empty($username)){
                return json([
                    'code' => 4000,
                    'message'=>"用户名已存在"
                ]);
            }
            if(empty($formdata["password"])){
                return json([
                    'code' => 4001,
                    'message'=>"密码不能为空"
                ]);
            }
            $formdata["admin_group_id"] = AdminGroupModel::field("id")->where("name","代理商")->value("id");

            if(empty($formdata["admin_group_id"])){
                return $this->display("请先添加对应的角色，再添加数据。");
            }
            $formdata["password"] =  md5($formdata["password"] . "zhinengyunjing");
            $result = $model->allowField(true)->save($formdata);

            if($result == 1){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //修改数据处理
    public function edit($id)
    {
        $model = new AgentModel;
        //接收ajax传递的值
        $ispost = $this->request->isPost();
        if($ispost){
            $formdata = $this->request->post();
            unset($formdata["province"]);
            unset($formdata["city"]);
            $formdata["region_id"] = $formdata["area"];
            $formdata["password"] = md5($formdata["password"] . "zhinengyunjing");
            $formdata["admin_group_id"] = AdminGroupModel::field("id")->where("name","代理商")->value("id");
            $result = $model->allowField(true)->save($formdata,['id'=>$id]);

            if($result == 1){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //删除单条记录
    public function delete($id)
    {
        $result = AgentModel::update(['deleted_at'=>date('Y-m-d H:i:s')],['id'=>$id]);//软删除
        //AlltimeModel::destroy($id,true);//真实删除
        if($result){
            return json([
                'code' => 200,
            ]);
        }

    }

    //批量删除
    public function deleteArr()
    {
        $ispost = $this->request->isPost();
        if ($ispost) {
            $idArr = $this->request->post();

            $result = AgentModel::where('id','exp','in('.implode(',',$idArr['id']).')')->update(['deleted_at'=>date('Y-m-d H:i:s')]);//软删除

            //AlltimeModel::destroy($id,true);//真实删除
            if($result){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //省市区三级联查
    public function province(){
        $province = \think\Db::query('SELECT id,p_id,name FROM '. $this->dbTablePrefix .'region where p_id=1');

        //$city = $reModel->field('id,name')->where('p_id',1)->select();
        //$area = $reModel->field('id,name')->where('p_id',1)->select();
        return json([
            'code' => 200,
            'data'=>$province,
        ]);
    }

    public function city($provCode){
        $city = \think\Db::query('SELECT id,p_id,name FROM '. $this->dbTablePrefix .'region where p_id='.$provCode);

        return json([
            'code' => 200,
            'data'=>$city,
        ]);
    }

    public function area($cityCode){
        $area = \think\Db::query('SELECT id,p_id,name FROM '. $this->dbTablePrefix .'region where p_id='.$cityCode);

        return json([
            'code' => 200,
            'data'=>$area,
        ]);
    }

}